const db = require("../model/db");

exports.findUserByName = async (username) => {
  const res = await db.q("select * from user where username=?", [username]);
  return res;
};

exports.findUserById = async (id) => {
  const res = await db.q(
    `SELECT u.id AS user_id,u.username,u.password,r.id AS role_id,r.name AS role_name FROM user u JOIN users_roles ur ON u.id = ur.userId JOIN roles r ON ur.rolesId = r.id WHERE u.id = ?`,
    [id]
  );
  return res;
};

exports.findUserAll = async () => {
  const res = await db.q("select * from user order by reg_time desc");
  return res;
};

//创建用户
exports.createUser = async (username, password, roleId,reg_time) => {
  // Step 1: 插入新用户到 user 表中
  const userRes = await db.q(
    "INSERT INTO user (username, password,reg_time) VALUES (?, ?,?)",
    [username, password, reg_time]
  );

  // 检查插入操作是否成功
  if (userRes.affectedRows > 0) {
    const newUserId = userRes.insertId;
    // Step 2: 插入用户与角色的关联到 users_roles 表中
    const roleRes = await db.q(
      "INSERT INTO users_roles (userId, rolesId) VALUES (?, ?)",
      [newUserId, roleId]
    );
    // 检查角色关联是否成功
    if (roleRes.affectedRows > 0) {
      return { id: newUserId, username, password, roleId };
    } else {
      throw new Error("Failed to associate user with role");
    }
  } else {
    throw new Error("User creation failed");
  }
};
